package a66weding.com.jiehuntong.activity.me;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.LoginActivity;
import a66weding.com.jiehuntong.activity.SMSFastLoginActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.VersionBean;
import a66weding.com.jiehuntong.common.UpdateAppController;
import a66weding.com.jiehuntong.common.UpdateConstants;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
/**
 * 我的-设置界面
 */
public class MeSettingActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mSecedeTv;
    private RelativeLayout mHeaderRightRlay;
    private RelativeLayout mNumSafeRlay;
    private RelativeLayout mFeedBackRlay;
    private RelativeLayout mRegardingRlay;
    private RelativeLayout mClearRlay;
    private PopupWindow mPopWindow;
    private RelativeLayout mUpdata;
    private PopupWindow mAreaPop;
    private boolean mustUpDate;
    private VersionBean mVersionBean;
    private int versionCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_settings);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeSettingActivity", this);
        initview();
    }

    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);
        mNumSafeRlay = (RelativeLayout) findViewById(R.id.rlay_me_set_numsafe);
        mFeedBackRlay = (RelativeLayout) findViewById(R.id.rlay_me_set_feedback);
        mRegardingRlay = (RelativeLayout) findViewById(R.id.rlay_me_set_regarding);
        mClearRlay = (RelativeLayout) findViewById(R.id.rlay_me_set_clear);
        mUpdata = (RelativeLayout) findViewById(R.id.rlay_updata);
        mSecedeTv = (TextView) findViewById(R.id.tv_secede);
        mBackContentTv.setText("我的");
        mHeaderTitleTv.setText("设置");
        mHeaderRightRlay.setVisibility(View.GONE);
        mBackLay.setOnClickListener(this);
        mNumSafeRlay.setOnClickListener(this);
        mFeedBackRlay.setOnClickListener(this);
        mRegardingRlay.setOnClickListener(this);
        mClearRlay.setOnClickListener(this);
        mUpdata.setOnClickListener(this);
        mSecedeTv.setOnClickListener(this);
        boolean isLogin = ((GlobalApplication) this.getApplication()).isLogin();
        if (!isLogin) {
            mSecedeTv.setVisibility(View.GONE);
            mNumSafeRlay.setVisibility(View.GONE);
            mSecedeTv.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.rlay_me_set_numsafe:
                intent.setClass(MeSettingActivity.this, MeSetNumSafeActivity.class);
                startActivity(intent);

                break;
            case R.id.rlay_me_set_feedback:
                intent.setClass(MeSettingActivity.this, MeSetSuggestActivity.class);
                startActivity(intent);
                break;
            case R.id.rlay_me_set_regarding:
                intent.setClass(MeSettingActivity.this, MeSetRegardingActivity.class);
                startActivity(intent);
                break;
            case R.id.rlay_me_set_clear:   //点击清除缓存，弹出对话框
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                    mPopWindow = null;
                }
                showMePopupWindow();
                break;
            case R.id.llay_header_back: //点击我的，退出当前界面
                finish();
                break;
            case R.id.rlay_updata: //检查更新
                getVersionInfo();
                break;
            case R.id.tv_secede:    //如果点击退出登录,则退出登录
                showLoginDialog(this, "是否确定退出?", "确定", "取消");
                break;
            case R.id.close_tv:
                UpdateAppController.stopUpdateService(this);
                if (mAreaPop != null) {
                    mAreaPop.dismiss();
                    mAreaPop = null;
                }
                if (mustUpDate) {
                    finish();
                }
                break;
            case R.id.update_btn:
                //让服务去更新
                if (MainActivity.isNewVersion && mVersionBean != null) {
                    boolean iswifi = NetStatusUtil.isWifi(MeSettingActivity.this);
                    boolean is4g = NetStatusUtil.is4G(MeSettingActivity.this);
                    if (mAreaPop != null) {
                        mAreaPop.dismiss();
                        if (mustUpDate) {
                            finish();
                        }
                    }
                    if (iswifi || is4g) {
                        Toast.makeText(getApplication(), "开始下载...", Toast.LENGTH_LONG).show();
                        UpdateAppController.startUpdateServiceForDown(this, UpdateConstants.ACTIVITY_FLAG, true, mVersionBean);
                    } else {
                        showDialog();
                    }
                }
                break;

        }
    }

    /**
     * 这是提醒用户非WIFI下载的提醒
     */
    private void showDialog() {
        AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("检测到您的网络处于非wifi状态或非4g状态,下载新版本将消耗一定的流量,是否继续下载?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UpdateAppController.startUpdateServiceForDown(MeSettingActivity.this, UpdateConstants.ACTIVITY_FLAG, true, mVersionBean);
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 新版版本更新UI
     *
     * @param versionBean
     */
    public void showOrderPopupWindowNew(VersionBean versionBean) {
        //填充更新弹窗UI以及找到对应的控件
        View contentView = LayoutInflater.from(MeSettingActivity.this).inflate(R.layout.new_dialog_update, null);
        TextView closeTv = (TextView) contentView.findViewById(R.id.close_tv);
        Button updateBtn = (Button) contentView.findViewById(R.id.update_btn);
        TextView versionTv = (TextView) contentView.findViewById(R.id.showversion_tv);
        //创建弹窗并设置
        mAreaPop = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        mAreaPop.setContentView(contentView);
        mAreaPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));
        mAreaPop.setOutsideTouchable(false);//外部不让触摸
        if (versionBean != null) {
            mustUpDate = versionBean.getData().getB_forcibly();
            if (mustUpDate) {//判断是否强制更新,如果强制更新点击弹窗外无效并且只能更新或者退出应用
                closeTv.setText("退出");
                mAreaPop.setFocusable(false);//当强制更新的时候失去焦点,关闭页面
            } else {
                mAreaPop.setFocusable(true);//非强制更新获得焦点可以点击返回键关闭弹窗
            }
            versionTv.setText("定的V" + versionBean.getData().getNew_versionName() + "版本,敬请体验。    ");
            /*更新日志内容 String update_log = versionBean.getData().getUpdate_log();
            if (update_log.contains("\\r")) {
                update_log = update_log.replaceAll("\\\\r", "\r\n");
            }*/
        }
        mAreaPop.showAtLocation(mNumSafeRlay, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //设置各个控件的点击响应
        closeTv.setOnClickListener(MeSettingActivity.this);
        updateBtn.setOnClickListener(MeSettingActivity.this);
    }

    public void showLoginDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, title, confirm, cancel, R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                CacheUtils.setBooleanToCache(MeSettingActivity.this, CacheUtils.islogin, false);    //把登录状态设置成false
                ((GlobalApplication) getApplication()).setLogin(false);//把Application设置成false
                CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, null);
                DataWareHourse.getInstance().setmUser(null);                    //清空登录保存User数据的bean
                Intent intent1 = new Intent(MeSettingActivity.this, SMSFastLoginActivity.class);//设置打开登录界面的意图
                ((GlobalApplication) getApplication()).getActivityManager().exitApp(); //获取到全部的Activity弹栈退出
                confirmDialog.dismiss();
                intent1.putExtra("isCanBack",false);
                startActivity(intent1);
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    public void showMePopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(MeSettingActivity.this).inflate(R.layout.pop_me_cache, null);
        mPopWindow = new PopupWindow(contentView,
                -1, -1, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        //设置各个控件
        LinearLayout mOkLay = (LinearLayout) contentView.findViewById(R.id.ll_me_ok);
        mOkLay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                mPopWindow = null;
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(MeSettingActivity.this).inflate(R.layout.activity_main, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof VersionBean) {
            VersionBean versionBean = (VersionBean) data;
            switch (versionBean.getResCode()) {
                case "0000":
                    if (versionBean != null) {
                        int new_versionCode = versionBean.getData().getNew_versionCode();
                        Log.e("Log", "StartupActivity onSucess: VersionBean=" + versionBean);
                        if (new_versionCode > versionCode) {
                            ((GlobalApplication) getApplication()).setDownNewVersion(true);
                            DataWareHourse.getInstance().setVersionBean(versionBean);
                            mVersionBean = DataWareHourse.getInstance().getVersionBean();
                            showOrderPopupWindowNew(mVersionBean);
                        } else {
                            CUtils.showToast("当前版本已经是最新版本！");
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("获取最新版本信息失败！");
    }

    /**
     * 获取版本信息
     */
    private void getVersionInfo() {
        versionCode = CUtils.getVersionCode(this);
        String url = RequestCode.GET_APP_NEW_VERSION;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, VersionBean.class,
                RequestCode.GET_APP_NEW_VERSION);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

}
